package com.example.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.easyexcel.dao.AssetInterfaceApiInfoMapper;
import com.example.easyexcel.dto.AssetInterfaceApiInfo;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
public class AssetInterfaceApiInfoListener extends AnalysisEventListener<AssetInterfaceApiInfo> {

    private final AssetInterfaceApiInfoMapper mapper;
    private static final int BATCH_SIZE = 256; // 批量插入大小
    private List<AssetInterfaceApiInfo> batchList = new ArrayList<>();

    public AssetInterfaceApiInfoListener(AssetInterfaceApiInfoMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void invoke(AssetInterfaceApiInfo dto, AnalysisContext context) {
        AssetInterfaceApiInfo entity = convertToEntity(dto);

        // 只有当 entity 不为 null（即有接口名称）时才添加到批量列表
        if (entity != null) {
            batchList.add(entity);
            if (batchList.size() >= BATCH_SIZE) {
                saveBatch();
                batchList.clear();
            }
        } else {
            log.debug("跳过 InterfaceName 为空的记录");
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!batchList.isEmpty()) {
            saveBatch();
        }
        log.info("API接口Excel导入完成");
    }

    private void saveBatch() {
        if (!batchList.isEmpty()) {
            mapper.insertBatch(batchList);
            log.info("批量插入API接口 {} 条数据", batchList.size());
        }
    }

    // 类级静态变量：用于生成全局唯一的自增序列（初始值为1，可根据需求调整）
    private static AtomicLong assetNoCounter = new AtomicLong(0);

    private AssetInterfaceApiInfo convertToEntity(AssetInterfaceApiInfo dto) {
        // 检查 InterfaceName 是否为空，如果为空则跳过此记录
        if (dto.getInterfaceName() == null || dto.getInterfaceName().trim().isEmpty()) {
            log.warn("跳过 InterfaceName 为空的记录");
            return null; // 返回 null 表示跳过此记录
        }

        AssetInterfaceApiInfo entity = new AssetInterfaceApiInfo();
        entity.setInterfaceName(dto.getInterfaceName());
        entity.setInterfaceUrl(dto.getInterfaceUrl());
        // 核心修改：生成"AP"+9位自增序列
        String assetNoPrefix = "AP"; // 2位固定编码
        long sequence = assetNoCounter.getAndIncrement(); // 原子递增，线程安全
        String assetNo = assetNoPrefix + String.format("%09d", sequence); // 格式化为9位（补零）
        entity.setAssetNo(assetNo); // 设置assetNo

        entity.setInterfaceTimeliness(dto.getInterfaceTimeliness());
        entity.setHistoryDataRange(dto.getHistoryDataRange());
        entity.setQuerySpan(dto.getQuerySpan());
        entity.setMaxTps(dto.getMaxTps());

        // 设置系统字段
        LocalDateTime now = LocalDateTime.now();
        entity.setCreateTime(now);
        entity.setUpdateTime(now);
        entity.setDelFlag(0L);
        entity.setDelTime(null);

        return entity;
    }
}

